package day10;

import java.util.Stack;

public class 有效的括号 {
    public boolean isValid(String s) {
        // 将字符串转换为字符数组
        char[] ch = s.toCharArray();
        int n = ch.length;
        //用栈解决
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            if (ch[i] == '(' || ch[i] == '[' || ch[i] == '{') {
                // 左括号入栈
                stack.push(ch[i]);
            } else {
                // 如果第一个是右括号
                if (stack.isEmpty()) {
                    return false;
                }
                //拿到栈头元素
                char tmp = stack.peek();
                // 进行匹配
                if (tmp == '(' && ch[i] == ')') {
                    //出栈
                    stack.pop();
                } else if (tmp == '[' && ch[i] == ']') {
                    stack.pop();
                } else if (tmp == '{' && ch[i] == '}') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }

        //检查栈
        if (!stack.isEmpty()) {
            return false;
        }
        return true;
    }

}
